import java.util.LinkedList;
import java.util.Queue;

class Solution1020 {
    public int numEnclaves(int[][] grid) {
         int m = grid.length , n = grid[0].length ;
         Queue<int[]> queue = new LinkedList<>() ;
         boolean[][] hash = new boolean[m][n];
        for(int i=0 ;i < m ; i ++){
            if(grid[i][0] == 1){
                queue.add(new int[]{i,0}) ; 
                hash[i][0] = true ;
                grid[i][0] = 0 ;
            }
            if(grid[i][n-1] == 1){
                queue.add(new int[]{i,n-1}) ; 
                hash[i][n-1] = true ;
                grid[i][n-1] = 0 ; 
            }
        }  
        for(int j=1 ; j < n-1 ; j ++ ){
             if(grid[0][j] == 1){
                queue.add(new int[]{0,j}) ; 
                hash[0][j] = true ;
                grid[0][j] = 0 ; 
            }
            if(grid[m-1][j] == 1){
                queue.add(new int[]{m-1 , j}) ; 
                hash[m-1][j] = true ;
                grid[m-1][j] = 0 ; 
            }
        }
        int[] dx = {0,0,1,-1} ;
        int[] dy = {1,-1,0,0} ; 
        while(!queue.isEmpty()){
             int[] arr = queue.poll() ;
             int a = arr[0] , b = arr[1] ;

            for(int i=0 ; i < 4 ; i ++){
              int x = a+dx[i]  , y = b+dy[i] ;
              if(x>=0 && x<m && y>=0 && y<n && hash[x][y]==false && grid[x][y] ==1){
                queue.add(new int[]{x, y});
                hash[x][y]= true ;
                grid[x][y] = 0 ;
              }
            }
        }
       
       int sum = 0 ;
        for(int i=0 ; i < m ; i ++){
            for(int j=0 ; j < n ; j ++){
                if(grid[i][j] == 1){
                    sum ++ ;
                }
            }
        }


return sum ;





    }
}